import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class MainJokeswarehouse {
	public static final String STARTPAGE = "http://www.jokeswarehouse.com/cgi-bin/category1.cgi?id=1";
	public static final String DOMAIN = "http://www.jokeswarehouse.com";

	public static String toURL(String url) {
		if (url.toLowerCase().startsWith("http://")) {
			return url;
		} else {
			return DOMAIN + url;
		}
	}

	public static String saveTo = null;
	static {
		saveTo = "E:\\Android\\SuperJokes\\autodownload\\Jokeswarehouse\\"
				+ new Date().getTime() + "\\";
		File f = new File(saveTo);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	public static void main(String[] args) throws IOException {
		Document doc = Jsoup.parse(new URL(STARTPAGE), 1000 * 30);
		String filePath = saveTo + File.separator + new Date().getTime();
		FileWriter fw = new FileWriter(new File(filePath));
		Elements jokeLinks = doc.select("a[target=jokebox]");
		for (int i = 0; i < jokeLinks.size(); i++) {
			try {
				Element each = jokeLinks.get(i);
				String jokeURL = toURL(each.attr("href"));
				Document jokeDoc = Jsoup.parse(new URL(jokeURL), 1000 * 30);
				// <font face="Arial" size="6">Blind Bunny</font>
				String jokeTitle = jokeDoc.select("font[size=6]").first().text();
				String jokeContent = jokeDoc.select("p font[size=2]").first()
						.html();
				System.out.println("title:" + jokeTitle);
				System.out.println("content:" + jokeContent);
				fw.write("titleFrog");
				fw.write(jokeTitle);
				fw.write("\r\n");
				fw.write("contentFrog");
				fw.write(jokeContent);
				fw.write("\r\n");
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			} 
		}
		fw.close();
	}

	private static String findNextPageA(Elements nextPageLinks) {
		for (int i = 0; i < nextPageLinks.size(); i++) {
			Element each = nextPageLinks.get(i);
			String text = each.text();
			if (text == null) {
				continue;
			}
			if (text.startsWith("Next Joke")) {
				return toURL(each.attr("href"));
			}
		}
		return null;
	}

}
